package com.goodfox.web.generic.organization.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.organization.entity.Organization;
import com.goodfox.web.generic.organization.service.OrganizationService;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.util.ParameterUtil;
import com.goodfox.web.generic.provide.util.AttributeUtil;

@Controller
@RequestMapping("/organization")
public class OrganizationController{

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(OrganizationController.class);
	
	/** 组织机构Service */
	@Autowired
	private OrganizationService organizationService;
	
	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;
	
	/**
	 * 进入组织机构管理首页页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationIndex.shtml")
	public String goOrganizationIndex(HttpServletRequest request,ModelMap model){
		logger.info("进入组织机构管理首页");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "organization/organizationIndex";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入上级组织机构查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationParentLookup.shtml")
	public String goOrganizationParentLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入上级组织机构查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "organization/organizationParentLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入地区查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goAreaLookup.shtml")
	public String goAreaLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入地区查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "area/areaLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	@RequestMapping(value="organizationTreeQuery.shtml")
	@ResponseBody
	public Map organizationTreeQuery(HttpServletRequest request){
		logger.info("执行组织机构查询");
		Map map=new HashMap();
	    Account loginAccount=(Account)request.getSession().getAttribute("loginAccount");
	    map.put("orgList", organizationService.queryOrganizationListByParentId(loginAccount.getOrgId()));
	    map.put("curOrgId", loginAccount.getOrgId());
		return map;
	}

	/**
	 * 进入组织机构信息页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationDetail.shtml")
	public String goOrganizationDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入组织机构信息页面");
		Organization organization=organizationService.getOrganization(ParameterUtil.getReqParaValue(request, "orgId"));
		model.put("org",organization);
		return "organization/organizationDetail";
	}
	
	/**
	 * 进入组织机构新增页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationAdd.shtml")
	public String goOrganizationAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入组织机构新增页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			Organization parentOrg=organizationService.getOrganization(ParameterUtil.getReqParaValue(request, "orgId"));
			model.put("parentOrg", parentOrg);
			model.put("scopeList", AttributeUtil.queryAttrListByType("机构类型"));
			return "organization/organizationAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行组织机构新增
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="organizationAdd.shtml")
	@ResponseBody
	public Map organizationAdd(HttpServletRequest request){
		logger.info("执行组织机构新增");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "organizationHome");
		rspMap.put("rel", "orgShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Organization entity=(Organization)entityService.fillEntity(request,Organization.class);
				organizationService.addOrganization(entity,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="新增成功！";
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("organizationAdd异常：",ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("organizationAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入组织机构修改页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationModify.shtml")
	public String goOrganizationModify(HttpServletRequest request,ModelMap model){
		logger.info("进入组织机构更新页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			Organization org=organizationService.getOrganization(ParameterUtil.getReqParaValue(request, "orgId"));
			model.put("org",org);
			Organization parentOrg=organizationService.getOrganization(org.getOrgIdParent());
			model.put("parentOrg",parentOrg);
			model.put("scopeList", AttributeUtil.queryAttrListByType("机构类型"));
			return "organization/organizationModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行组织机构修改
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="organizationModify.shtml")
	@ResponseBody
	public Map organizationModify(HttpServletRequest request){
		logger.info("执行组织机构更新");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "organizationHome");
		rspMap.put("rel", "orgShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Organization newEny=(Organization)entityService.fillEntity(request,Organization.class);
				Organization oldEny=organizationService.getOrganization(newEny.getOrgId());
				organizationService.modifyOrganization(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("organizationModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("organizationModify rspMap:"+rspMap);
		return rspMap;
	}

	/**
	 * 执行组织机构删除操作，数据物理删除
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="organizationRemove.shtml")
	@ResponseBody
	public Map organizationRemove(HttpServletRequest request){
		logger.info("执行组织机构移除");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "organizationHome");
		rspMap.put("rel", "orgShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				String orgId=ParameterUtil.getReqParaValue(request, "orgId");
				Organization entity=organizationService.getOrganization(orgId);
				boolean isExec=true;
				if(isExec){
					if(entity.getSubCount()>0){
						isExec=false;
						message="该机构中有下级机构，不能移除！";
					}
				}
				if(isExec){
					if(entity.getMemCount()>0){
						isExec=false;
						message="该机构中有所属成员，不能移除！";
					}
				}
				if(isExec){
					organizationService.removeOrganization(entity,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="移除成功！";
				}
			}catch(Exception ex){
				logger.error("organizationRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("organizationRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 组织机构判断
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="haveOrganization.shtml")
	@ResponseBody
	public Map haveOrganization(@RequestBody Map reqMap){
		logger.info("组织机构判断");
		Map rspMap=new HashMap();
		boolean result=false;
		String msg="请选择一个组织机构";
		try{
			Organization org=organizationService.getOrganization(String.valueOf(reqMap.get("orgId")));
			if(org!=null){
				result=true;
			}
		}catch(Exception ex){
			logger.error("isHave异常：",ex);
		}
		rspMap.put("result", result);
		rspMap.put("msg", msg);
		logger.debug("isHave rspMap:"+rspMap);
		return rspMap;
	}
	
}
